<template>
  <div class="improvement-suggestions">
    <el-card class="suggestions-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">改进建议</h1>
          <p class="page-subtitle">基于评价分析生成的个性化改进建议</p>
        </div>
        <div class="action-section">
          <el-button @click="goBackToList" icon="ArrowLeft">
            返回评价列表
          </el-button>
          <el-button type="primary" @click="refreshSuggestions" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 筛选条件 -->
    <el-card class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="司机ID">
          <el-input v-model="filterForm.driverId" placeholder="请输入司机ID" clearable />
        </el-form-item>
        <el-form-item label="建议类型">
          <el-select v-model="filterForm.suggestionType" placeholder="选择建议类型" clearable>
            <el-option label="服务态度" value="service_attitude" />
            <el-option label="驾驶技术" value="driving_skill" />
            <el-option label="车辆状况" value="vehicle_condition" />
            <el-option label="沟通能力" value="communication" />
            <el-option label="时间观念" value="time_management" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="filterForm.priority" placeholder="选择优先级" clearable>
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 建议列表 -->
    <div class="suggestions-grid">
      <el-card 
        v-for="suggestion in suggestionsList" 
        :key="suggestion.id" 
        class="suggestion-card"
        :class="getPriorityClass(suggestion.priority)"
      >
        <div class="suggestion-header">
          <div class="suggestion-type">
            <el-tag :type="getTypeTagType(suggestion.suggestion_type)" size="small">
              {{ getTypeLabel(suggestion.suggestion_type) }}
            </el-tag>
            <el-tag :type="getPriorityTagType(suggestion.priority)" size="small">
              {{ getPriorityLabel(suggestion.priority) }}
            </el-tag>
          </div>
          <div class="suggestion-actions">
            <el-button type="success" size="small" @click="markAsImplemented(suggestion)">
              标记完成
            </el-button>
          </div>
        </div>
        
        <div class="suggestion-content">
          <h3 class="suggestion-title">{{ getSuggestionTitle(suggestion) }}</h3>
          <p class="suggestion-description">{{ getSuggestionDescription(suggestion) }}</p>
          
          <div class="suggestion-details">
            <div class="detail-item">
              <span class="detail-label">司机ID:</span>
              <span class="detail-value">{{ suggestion.analysis?.order_rating?.driver_id }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">订单号:</span>
              <span class="detail-value">{{ suggestion.analysis?.order_rating?.order?.order_number }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">生成时间:</span>
              <span class="detail-value">{{ formatDate(suggestion.generated_time) }}</span>
            </div>
          </div>
          
          <div class="suggestion-reasoning">
            <h4>分析依据</h4>
            <p>{{ getSuggestionReasoning(suggestion) }}</p>
          </div>
          
          <div class="suggestion-actions" v-if="suggestion.implementation_steps">
            <h4>实施步骤</h4>
            <ol class="implementation-steps">
              <li v-for="(step, index) in suggestion.implementation_steps" :key="index">
                {{ step }}
              </li>
            </ol>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="pagination.total > 0">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 空状态 -->
    <el-empty 
      v-if="suggestionsList.length === 0 && !loading" 
      description="暂无改进建议"
      :image-size="200"
    >
      <el-button type="primary" @click="refreshSuggestions">刷新</el-button>
    </el-empty>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { evaluationAPI } from '@/api/evaluation'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const suggestionsList = ref([])

// 筛选表单
const filterForm = ref({
  driverId: '',
  suggestionType: '',
  priority: ''
})

// 分页
const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0
})

// 初始化页面
onMounted(() => {
  loadSuggestions()
})

// 加载建议列表
async function loadSuggestions() {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      page_size: pagination.value.pageSize
    }

    // 添加筛选条件
    if (filterForm.value.driverId) {
      params.driver_id = filterForm.value.driverId
    }
    if (filterForm.value.suggestionType) {
      params.suggestion_type = filterForm.value.suggestionType
    }
    if (filterForm.value.priority) {
      params.priority = filterForm.value.priority
    }

    console.log('API调用参数:', params)
    const response = await evaluationAPI.getImprovementSuggestions(
      params.driver_id || null,
      params.page,
      params.page_size
    )
    
    console.log('改进建议API响应:', response)
    if (response.data) {
      suggestionsList.value = response.data.data || []
      pagination.value.total = response.data.total || 0
      console.log('改进建议数据:', suggestionsList.value)
    }
  } catch (error) {
    console.error('加载改进建议失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 应用筛选
function applyFilter() {
  pagination.value.page = 1
  loadSuggestions()
}

// 重置筛选
function resetFilter() {
  filterForm.value = {
    driverId: '',
    suggestionType: '',
    priority: ''
  }
  pagination.value.page = 1
  loadSuggestions()
}

// 刷新建议
async function refreshSuggestions() {
  loading.value = true
  await loadSuggestions()
  ElMessage.success('数据已刷新')
  loading.value = false
}

// 标记为已完成
async function markAsImplemented(suggestion) {
  try {
    await ElMessageBox.confirm(
      '确认将此建议标记为已完成？',
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里可以调用API更新建议状态
    ElMessage.success('已标记为完成')
    await loadSuggestions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 获取优先级样式类
function getPriorityClass(priority) {
  const classes = {
    high: 'priority-high',
    medium: 'priority-medium',
    low: 'priority-low'
  }
  return classes[priority] || ''
}

// 获取类型标签类型
function getTypeTagType(type) {
  const types = {
    service_attitude: 'primary',
    driving_skill: 'success',
    vehicle_condition: 'warning',
    communication: 'info',
    time_management: 'danger'
  }
  return types[type] || 'default'
}

// 获取优先级标签类型
function getPriorityTagType(priority) {
  const types = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return types[priority] || 'default'
}

// 获取类型标签
function getTypeLabel(type) {
  const labels = {
    service_attitude: '服务态度',
    driving_skill: '驾驶技术',
    vehicle_condition: '车辆状况',
    communication: '沟通能力',
    time_management: '时间观念'
  }
  return labels[type] || type
}

// 获取优先级标签
function getPriorityLabel(priority) {
  const labels = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return labels[priority] || priority
}

// 获取建议标题
function getSuggestionTitle(suggestion) {
  const typeLabels = {
    'service_attitude': '服务态度改进建议',
    'driving_skill': '驾驶技术改进建议',
    'vehicle_condition': '车辆状况改进建议',
    'communication': '沟通能力改进建议',
    'time_management': '时间观念改进建议'
  }
  return typeLabels[suggestion.suggestion_type] || '改进建议'
}

// 获取建议描述
function getSuggestionDescription(suggestion) {
  if (!suggestion.suggestion_content) {
    return '暂无描述'
  }
  
  // 提取第一段作为描述
  const content = suggestion.suggestion_content
  const lines = content.split('\n')
  for (let line of lines) {
    line = line.trim()
    if (line && !line.startsWith('#') && !line.startsWith('*') && !line.startsWith('-')) {
      return line.length > 100 ? line.substring(0, 100) + '...' : line
    }
  }
  return '基于评价分析生成的改进建议'
}

// 获取分析依据
function getSuggestionReasoning(suggestion) {
  if (!suggestion.suggestion_content) {
    return '基于评价分析生成'
  }
  
  // 清理Markdown格式
  let content = suggestion.suggestion_content
    .replace(/###/g, '')
    .replace(/\*\*/g, '')
    .replace(/\*/g, '')
    .replace(/^- /g, '• ')
    .replace(/\n\n/g, '\n')
    .trim()
  
  // 提取关键信息
  const lines = content.split('\n')
  const keyInfo = []
  
  for (let line of lines) {
    line = line.trim()
    if (line && (line.includes('问题') || line.includes('改进') || line.includes('建议') || line.includes('分析'))) {
      keyInfo.push(line)
      if (keyInfo.length >= 2) break
    }
  }
  
  // 如果没有找到关键信息，返回前100个字符
  if (keyInfo.length === 0) {
    return content.length > 100 ? content.substring(0, 100) + '...' : content
  }
  
  return keyInfo.join(' ')
}

// 分页处理
function handleSizeChange(size) {
  pagination.value.pageSize = size
  pagination.value.page = 1
  loadSuggestions()
}

function handleCurrentChange(page) {
  pagination.value.page = page
  loadSuggestions()
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 返回评价分析列表
function goBackToList() {
  router.push('/evaluation/list')
}
</script>

<style scoped>
.improvement-suggestions {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.suggestions-header {
  margin-bottom: 20px;
  border-radius: 12px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-section {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
  border-radius: 12px;
}

.suggestions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.suggestion-card {
  border-radius: 12px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.suggestion-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.suggestion-card.priority-high {
  border-left: 4px solid #f56c6c;
}

.suggestion-card.priority-medium {
  border-left: 4px solid #e6a23c;
}

.suggestion-card.priority-low {
  border-left: 4px solid #409eff;
}

.suggestion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.suggestion-type {
  display: flex;
  gap: 8px;
}

.suggestion-actions {
  display: flex;
  gap: 8px;
}

.suggestion-content {
  margin-top: 16px;
}

.suggestion-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.suggestion-description {
  margin: 0 0 16px 0;
  color: #606266;
  line-height: 1.6;
}

.suggestion-details {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  font-weight: 500;
  color: #606266;
}

.detail-value {
  color: #303133;
}

.suggestion-reasoning {
  margin-bottom: 16px;
}

.suggestion-reasoning h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.suggestion-reasoning p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.implementation-steps {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  line-height: 1.6;
}

.implementation-steps li {
  margin-bottom: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .suggestions-grid {
    grid-template-columns: 1fr;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .action-section {
    justify-content: center;
  }
  
  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .suggestion-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .suggestion-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 